import { NextResponse } from 'next/server';
import { Todo } from '../../../lib/db';

// 获取所有待办事项
export async function GET() {
  try {
    const todos = await Todo.findAll({
      order: [['createdAt', 'DESC']]
    });
    return NextResponse.json(todos);
  } catch (error) {
    console.error('获取待办事项失败:', error);
    return NextResponse.json({ error: '获取待办事项失败' }, { status: 500 });
  }
}

// 创建新的待办事项
export async function POST(request: Request) {
  try {
    const { text } = await request.json();
    if (!text) {
      return NextResponse.json({ error: '待办事项内容不能为空' }, { status: 400 });
    }

    const todo = await Todo.create({
      text,
      completed: false
    });
    
    return NextResponse.json(todo);
  } catch (error) {
    console.error('创建待办事项失败:', error);
    return NextResponse.json({ error: '创建待办事项失败' }, { status: 500 });
  }
}

// 更新待办事项状态
export async function PUT(request: Request) {
  try {
    const { id, completed, text } = await request.json();
    if (!id) {
      return NextResponse.json({ error: '待办事项ID不能为空' }, { status: 400 });
    }

    const updateData: { completed?: boolean; text?: string } = {};
    if (typeof completed !== 'undefined') {
      updateData.completed = completed;
    }
    if (typeof text !== 'undefined') {
      updateData.text = text;
    }

    await Todo.update(updateData, {
      where: { id }
    });

    const updatedTodo = await Todo.findByPk(id);
    return NextResponse.json(updatedTodo);
  } catch (error) {
    console.error('更新待办事项失败:', error);
    return NextResponse.json({ error: '更新待办事项失败' }, { status: 500 });
  }
}

// 删除待办事项
export async function DELETE(request: Request) {
  try {
    const { id } = await request.json();
    if (!id) {
      return NextResponse.json({ error: '待办事项ID不能为空' }, { status: 400 });
    }

    await Todo.destroy({
      where: { id }
    });
    
    return NextResponse.json({ success: true });
  } catch (error) {
    console.error('删除待办事项失败:', error);
    return NextResponse.json({ error: '删除待办事项失败' }, { status: 500 });
  }
}